/**
 * 
 * @author Sunix
 * @date   2013-5-8
 * @Email  SunixSky@gmail.com
 * 
 */	
package sunix.animationPlayer{
	
	import sunix.animationPlayer.events.AnimationPlayerEvent;
	import sunix.interfaces.IFrame;
	
	public class AnimationPlayerManager implements IFrame{
		
		protected var maxSize:int = 0;        //对象池最大值
		protected var growthSize:int = 0;     //增长值
		protected var pool:Vector.<AnimationPlayer>;  //播放器存储池
		protected var counter:uint; //计数器
		
		protected static var self:AnimationPlayerManager;     //播放器管理器实例
		
		/**
		 * 构造函数 
		 * 
		 */		
		public function AnimationPlayerManager():void{}
		
		/**
		 * 初始化 
		 * 
		 */		
		public function init(max:int,growth:int=10):void{
			maxSize = max;
			growthSize = growth;
			counter = max;
			pool = new Vector.<AnimationPlayer>(maxSize);
			var i:int = maxSize;
			while(--i > -1)
				pool[i] = createAnimationPlayer();
		}
		
		/**
		 * 获取播放器
		 *  
		 * @return 
		 * 
		 */		
		public function getAnimationPlayer():AnimationPlayer{
			if(counter>0)
				return pool[--counter];
			var i:int = growthSize;  //当池中的对象用尽时，允许其增长；
			while(--i > -1)
				pool.unshift(createAnimationPlayer());
			counter = growthSize;
			return getAnimationPlayer();
		}
		
		/**
		 * 释放回收
		 *  
		 * @param player
		 * 
		 */		
		public function disposeAnimationPlayer(player:AnimationPlayer):void{
			player.dispose();
			pool[counter++] = player; 
		}
		
		/**
		 * 帧渲染 
		 * 
		 */		
		public function enterFrame():void{
			for each(var player:AnimationPlayer in pool){
				if(player.active)
					player.render();
			}
		}
		
		/**
		 * 获取单例
		 *  
		 * @return 
		 * 
		 */		
		public static function get instance():AnimationPlayerManager{
			if(!self)
				self = new AnimationPlayerManager();
			return self;
		}
		
		/**
		 * 创建播放器对象
		 *  
		 * @return 
		 * 
		 */		
		protected function createAnimationPlayer():AnimationPlayer{
			var player:AnimationPlayer = new AnimationPlayer();
			player.addEventListener(AnimationPlayerEvent.DESTORY,onDestory);
			return player;
		}
		
		/**
		 * 销毁方法
		 *  
		 * @param event
		 * 
		 */		
		protected function onDestory(event:AnimationPlayerEvent):void{
			var player:AnimationPlayer = event.target as AnimationPlayer;
			disposeAnimationPlayer(player);
		}
	}
}